import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_course_item_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_course_video_item_widget.dart';
import 'package:get/get.dart';

import '../../bean/bean_train.dart';
import '../../bean/bean_video_course.dart';
import '../../utils/toast_utils.dart';
import '../common/common_loading_dialog.dart';
import 'controller/train_history_controller.dart';
import 'demo1/list_train_sign_item_widget.dart';

class TrainHistoryWidget extends StatefulWidget {
  final String tag;

  //培训ID
  final TrainApproveBean approveBean;
  final bool shrinkWrap;

  const TrainHistoryWidget(
      {Key key,
      @required this.tag,
      @required this.approveBean,
      this.shrinkWrap = false})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TrainHistoryWidgetState();
  }
}

class _TrainHistoryWidgetState extends State<TrainHistoryWidget>
    with TickerProviderStateMixin {
  TrainHistoryController _historyController;
  TabController _tabController;
  List<Tab> tableList = [
    Tab(
      text: "我的学习记录",
    ),
    Tab(
      text: "学习进度",
    ),
  ];

  @override
  void initState() {
    super.initState();
    _historyController = Get.put(
      TrainHistoryController(widget.approveBean.trainId),
      tag: widget.tag,
    );
    _tabController = new TabController(length: tableList.length, vsync: this);

    Future.delayed(Duration.zero, () async {
      await _historyController.requestListFunction();
      _historyController.getMyTrainDetailsFunction();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      id: "root",
      tag: widget.tag,
      builder: (TrainHistoryController controller) {
        return buildAnimatedSwitcher(context);
      },
    );
  }

  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(

        //动画执行切换时间
        duration: const Duration(milliseconds: 200),
        //动画构建器 构建指定动画类型
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return FadeTransition(child: child, opacity: animation);
        },
        //执行动画的子 Widget
        //只有子 Widget 被切换时才会触发动画
        child: buildMyScoreHisIntegralWidget());
  }

  buildMyScoreHisIntegralWidget() {
    bool _isLoading = _historyController.getIsLoading();
    if (_isLoading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    List<SignRecoderBean> _list = _historyController.getList();

    // if (_list == null || _list.length == 0) {
    //   return NoDataWidget(
    //     text: "暂无上课记录",
    //     clickCallBack: () {
    //       _historyController.requestListFunction(click: true);
    //     },
    //   );
    // }
    if (widget.shrinkWrap) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(top: 10, bottom: 10),
            child: TabBar(
              indicatorColor: Colors.blue[900],
              labelColor: Colors.blue[900],
              isScrollable: true,
              controller: _tabController,
              indicatorSize: TabBarIndicatorSize.label,
              onTap: (int index) {
                _currentIndex = index;
                _historyController.update(["list"]);
              },
              tabs: tableList,
            ),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 8, left: 4, right: 4),
            padding: EdgeInsets.only(bottom: 12),
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Color(0xFFF8F9FC), Color(0xFFF2F5F8)]),
                borderRadius: BorderRadius.all(Radius.circular(12)),
                border: Border.all(
                  color: Colors.white,
                )),
            child: GetBuilder(
              id: "list",
              tag: widget.tag,
              builder: (TrainHistoryController controller) {
                return buildListViewAnimatedSwitcher(context);
              },
            ),
          ),
        ],
      );
    }
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          width: double.infinity,
          height: 74,
          padding: EdgeInsets.only(top: 10),
          child: Stack(
            alignment: Alignment.center,
            children: [
              Text(
                "上课记录",
                style: TextStyle(fontSize: 18),
              ),
            ],
          ),
          color: Colors.white,
        ),
        Expanded(
          child: Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 1),
            child: RefreshIndicator(
              onRefresh: () async {
                await _historyController.requestListFunction();
                ToastUtils.showToast("已刷新");
                return true;
              },
              child: buildListView(),
            ),
          ),
        )
      ],
    );
  }

  AnimatedSwitcher buildListViewAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 200),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },
      //执行动画的子 Widget
      //只有子 Widget 被切换时才会触发动画
      child: Container(
        key: UniqueKey(),
        child: buildMyListWidget(),
      ),
    );
  }

  int _currentIndex = 0;

  buildMyListWidget() {
    if (_currentIndex == 0) {
      return buildListView();
    }
    if (_currentIndex == 1) {
      return Padding(
          padding: EdgeInsets.only(left: 10), child: buildListView2());
    }
    return SizedBox();
  }

  buildListView() {
    List<SignRecoderBean> _list = _historyController.getList();
    return ListView.builder(
      padding: EdgeInsets.zero,
      shrinkWrap: widget.shrinkWrap,
      physics: widget.shrinkWrap
          ? NeverScrollableScrollPhysics()
          : BouncingScrollPhysics(),
      //条目个数
      itemCount: _list.length,
      //每个子条目的样式
      itemBuilder: (BuildContext context, int index) {
        SignRecoderBean recoderBean = _list[index];
        return ListItemTrainRecoderItem(
          list: _list,
          index: index,
        );
      },
    );
  }

  ListView buildListView2() {
    int count = 0;
    TrainBean _trainBean = _historyController.getContentTrainBean();

    if (_trainBean.courseList != null) {
      count = _trainBean.courseList.length;
    }
    if (_trainBean.videoCourseEntityList != null) {
      count = count + _trainBean.videoCourseEntityList.length;
    }
    return ListView.builder(
      shrinkWrap: widget.shrinkWrap,
      physics: widget.shrinkWrap
          ? NeverScrollableScrollPhysics()
          : BouncingScrollPhysics(),
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        if (_trainBean.courseList.length > 0 &&
            index < _trainBean.courseList.length) {
          CourseAndTeacherBean cubean = _trainBean.courseList[index];
          return TrainTeacherCourseItemWidget(
            cubean: cubean,
            index: index,
            isScaffold: true,
          );
        } else {
          BeanVideoCourse beanVideoCourse = _trainBean
              .videoCourseEntityList[index - _trainBean.courseList.length];
          return TrainTeacherCourseVideoItemWidget(
            beanVideoCourse: beanVideoCourse,
            index: index,
            isScaffold: true,
            trainId: _trainBean.trainId,
          );
        }
      },
    );
  }
}
